import ApiService from './api';
import { Shop, PaginationParams, PaginatedResponse } from '../types';

// 店铺查询参数
export interface ShopQueryParams extends PaginationParams {
  keyword?: string;
  status?: 'pending' | 'approved' | 'rejected' | 'suspended';
  ownerId?: string;
  minRating?: number;
  maxRating?: number;
}

// 店铺创建/更新数据
export interface ShopFormData {
  name: string;
  description: string;
  logo: string;
  banner: string;
  ownerId: string;
  categories: string[];
  type: 'official' | 'flagship' | 'authorized' | 'personal';
  status: 'active' | 'inactive' | 'suspended' | 'pending';
  contact?: {
    phone?: string;
    email?: string;
    address?: string;
    workingHours?: string;
  };
  announcement?: string;
  tags?: string[];
}

// 店铺审核数据
export interface ShopApprovalData {
  status: 'approved' | 'rejected';
  reason?: string;
}

// 店铺服务
export class ShopService {
  // 获取店铺列表
  static async getShops(params: ShopQueryParams): Promise<PaginatedResponse<Shop>> {
    const response = await ApiService.get<PaginatedResponse<Shop>>('/admin/shops', params);
    return response;
  }

  // 获取店铺详情
  static async getShop(id: string): Promise<Shop> {
    const response = await ApiService.get<any>(`/admin/shops/${id}`);
    // axios响应结构: response.data = {success: true, data: shopDetails}
    // 所以我们需要返回 response.data.data
    return response.data?.data || response.data || response;
  }

  // 创建店铺
  static async createShop(data: ShopFormData): Promise<Shop> {
    const response = await ApiService.post<any>('/admin/shops', data);
    return response.data?.data || response.data || response;
  }

  // 更新店铺
  static async updateShop(id: string, data: Partial<ShopFormData>): Promise<Shop> {
    const response = await ApiService.put<any>(`/admin/shops/${id}`, data);
    return response.data?.data || response.data || response;
  }

  // 删除店铺
  static async deleteShop(id: string): Promise<void> {
    await ApiService.delete(`/admin/shops/${id}`);
  }

  // 审核店铺
  static async approveShop(id: string, data: ShopApprovalData): Promise<Shop> {
    return await ApiService.post<Shop>(`/admin/shops/${id}/approve`, data);
  }

  // 暂停店铺
  static async suspendShop(id: string, reason?: string): Promise<Shop> {
    return await ApiService.post<Shop>(`/admin/shops/${id}/suspend`, { reason });
  }

  // 恢复店铺
  static async resumeShop(id: string): Promise<Shop> {
    return await ApiService.post<Shop>(`/admin/shops/${id}/resume`);
  }

  // 获取待审核店铺
  static async getPendingShops(params: PaginationParams): Promise<PaginatedResponse<Shop>> {
    return await ApiService.get<PaginatedResponse<Shop>>('/admin/shops/pending', params);
  }

  // 获取店铺统计信息
  static async getShopStats(id: string): Promise<{
    totalProducts: number;
    totalOrders: number;
    totalSales: number;
    totalRevenue: number;
    rating: number;
    reviewCount: number;
  }> {
    return await ApiService.get(`/admin/shops/${id}/stats`);
  }

  // 获取店铺销售数据
  static async getShopSalesData(id: string, period: 'day' | 'week' | 'month' = 'month'): Promise<{
    salesData: Array<{
      date: string;
      sales: number;
      orders: number;
      revenue: number;
    }>;
    totalSales: number;
    totalOrders: number;
    totalRevenue: number;
  }> {
    return await ApiService.get(`/admin/shops/${id}/sales-data`, { period });
  }

  // 获取店铺商品列表
  static async getShopProducts(id: string, params: PaginationParams): Promise<PaginatedResponse<any>> {
    return await ApiService.get<PaginatedResponse<any>>(`/admin/shops/${id}/products`, params);
  }

  // 获取店铺订单列表
  static async getShopOrders(id: string, params: PaginationParams): Promise<PaginatedResponse<any>> {
    return await ApiService.get<PaginatedResponse<any>>(`/admin/shops/${id}/orders`, params);
  }

  // 获取店铺评价列表
  static async getShopReviews(id: string, params: PaginationParams): Promise<PaginatedResponse<any>> {
    return await ApiService.get<PaginatedResponse<any>>(`/admin/shops/${id}/reviews`, params);
  }

  // 获取热门店铺
  static async getPopularShops(limit: number = 10): Promise<Shop[]> {
    return await ApiService.get<Shop[]>('/admin/shops/popular', { limit });
  }

  // 获取新店铺
  static async getNewShops(limit: number = 10): Promise<Shop[]> {
    return await ApiService.get<Shop[]>('/admin/shops/new', { limit });
  }

  // 导出店铺数据
  static async exportShops(params: ShopQueryParams): Promise<void> {
    await ApiService.download('/admin/shops/export', 'shops.xlsx');
  }

  // 获取店铺分析报告
  static async getShopAnalytics(id: string, period: 'week' | 'month' | 'quarter' = 'month'): Promise<{
    overview: {
      totalRevenue: number;
      totalOrders: number;
      totalProducts: number;
      averageOrderValue: number;
    };
    trends: {
      revenueTrend: number;
      orderTrend: number;
      productTrend: number;
    };
    topProducts: Array<{
      productId: string;
      name: string;
      sales: number;
      revenue: number;
    }>;
    customerAnalysis: {
      newCustomers: number;
      returningCustomers: number;
      customerRetentionRate: number;
    };
  }> {
    return await ApiService.get(`/admin/shops/${id}/analytics`, { period });
  }

  // 设置店铺推荐状态
  static async setShopFeatured(id: string, isFeatured: boolean): Promise<Shop> {
    return await ApiService.patch<Shop>(`/admin/shops/${id}/featured`, { isFeatured });
  }

  // 获取审核历史
  static async getApprovalHistory(params: {
    page?: number;
    limit?: number;
    keyword?: string;
    action?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<PaginatedResponse<{
    id: string;
    shopId: string;
    shopName: string;
    action: 'approved' | 'rejected' | 'suspended' | 'resumed';
    reason?: string;
    operator: string;
    operatorId: string;
    createdAt: string;
    previousStatus: string;
    newStatus: string;
  }>> {
    return await ApiService.get<PaginatedResponse<any>>('/admin/shops/approval-history', params);
  }

  // 获取总体统计数据
  static async getOverallStats(params: {
    startDate?: string;
    endDate?: string;
    shopId?: string;
  }): Promise<{
    totalShops: number;
    activeShops: number;
    totalRevenue: number;
    totalOrders: number;
    averageRating: number;
    growthRate: number;
  }> {
    return await ApiService.get('/admin/shops/overall-stats', params);
  }

  // 获取商店排行榜
  static async getShopRankings(params: {
    startDate?: string;
    endDate?: string;
    limit?: number;
  }): Promise<Array<{
    shopId: string;
    shopName: string;
    shopLogo: string;
    revenue: number;
    orders: number;
    rating: number;
    growth: number;
    rank: number;
  }>> {
    return await ApiService.get('/admin/shops/rankings', params);
  }

  // 获取营收趋势
  static async getRevenueTrend(params: {
    startDate?: string;
    endDate?: string;
    shopId?: string;
  }): Promise<Array<{
    date: string;
    revenue: number;
    orders: number;
  }>> {
    return await ApiService.get('/admin/shops/revenue-trend', params);
  }

  // 获取分类统计
  static async getCategoryStats(params: {
    startDate?: string;
    endDate?: string;
    shopId?: string;
  }): Promise<Array<{
    category: string;
    revenue: number;
    count: number;
  }>> {
    return await ApiService.get('/admin/shops/category-stats', params);
  }

  // 获取店铺客服列表
  static async getShopCustomerServices(id: string): Promise<any[]> {
    return await ApiService.get<any[]>(`/admin/shops/${id}/customer-services`);
  }

  // 添加店铺客服
  static async addShopCustomerService(id: string, data: {
    userId: string;
    name: string;
    avatar?: string;
  }): Promise<any> {
    return await ApiService.post(`/admin/shops/${id}/customer-services`, data);
  }

  // 移除店铺客服
  static async removeShopCustomerService(shopId: string, serviceId: string): Promise<void> {
    await ApiService.delete(`/admin/shops/${shopId}/customer-services/${serviceId}`);
  }

  // 批量操作店铺
  static async batchActionShops(ids: string[], action: 'approve' | 'reject' | 'suspend' | 'resume', data?: any): Promise<void> {
    await ApiService.post('/admin/shops/batch-action', { ids, action, data });
  }

  // 批量删除店铺
  static async batchDeleteShops(ids: string[]): Promise<void> {
    await ApiService.post('/admin/shops/batch-delete', { ids });
  }

  // 更新店铺状态
  static async updateShopStatus(id: string, status: 'active' | 'inactive' | 'suspended'): Promise<Shop> {
    return await ApiService.patch<Shop>(`/admin/shops/${id}/status`, { status });
  }

  // 批量更新店铺状态
  static async updateShopsStatus(ids: string[], status: 'active' | 'inactive' | 'suspended'): Promise<void> {
    await ApiService.post('/admin/shops/batch-status', { ids, status });
  }
}

export default ShopService;
